<template>
  <div class="table-box">
    <ProTable
      ref="proTableRef"
      title="文件监控数据"
      :indent="20"
      :columns="columns"
      :search-columns="searchColumns"
      :request-api="getTableList"
      row-key="id"
    >
      <!-- 表格 header 按钮 -->
      <template #tableHeader="scope">
        <!-- <el-button type="primary" :icon="Plus" @click="openAdd">
          新增记录
        </el-button>
        <el-button type="success" :icon="Download" plain @click="exportData" :disabled="!scope.isSelected">
          导出选中
        </el-button>
        <el-button type="info" :icon="DocumentCopy" @click="getStatistics">
          统计信息
        </el-button> -->
      </template>
      <template #operation="{ row }">
        <el-button type="primary" link :icon="EditPen" @click="openEdit(row)">
          编辑
        </el-button>
        <!--<el-button type="info" link :icon="View" @click="testImageAccess(row.fileUrl)" v-if="row.fileUrl">
          测试访问
        </el-button>
         <el-button type="info" link :icon="View" @click="viewFileRecord(row)">
          查看
        </el-button>
        <el-button type="success" link :icon="Download" @click="downloadFileRecord(row)">
          下载
        </el-button>
        <el-button type="warning" link :icon="RefreshRight" @click="reprocessFile(row)" v-if="row.status === 'FAILED'">
          重处理
        </el-button> -->
        <el-button type="danger" link :icon="Delete" @click="deleteRecord(row)">
          删除
        </el-button>
      </template>
    </ProTable>
    <FileRecordEdit ref="fileRecordEditRef" />
    <StatisticsDialog ref="statisticsDialogRef" />
  </div>
</template>

<script setup lang="ts">
import { ref, h, onBeforeUnmount } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { Plus, Download, DocumentCopy, View, EditPen, RefreshRight, Delete } from '@element-plus/icons-vue';
import ProTable from '@/components/ProTable/index.vue';
import FileRecordEdit from './components/FileRecordEdit.vue';
import StatisticsDialog from './components/StatisticsDialog.vue';
import AuthenticatedImage from './components/AuthenticatedImage.vue';
import type { ColumnProps, ProTableInstance, SearchProps } from '@/components/ProTable/interface';
import { 
  getMonitorFileRecordList, 
  editMonitorFileRecord, 
  edit2MonitorFileRecord,
  addMonitorFileRecord,
  deleteMonitorFileRecord,
  downloadFile,
  reprocessFailedFile,
  getFileStatistics
} from '@/api/modules/datainfo/statisticsData';
import http from '@/api';
import type { MonitorFileRecordQuery, MonitorFileRecordInfo } from '@/api/types/datainfo/statisticsData';
import { useHandleData } from '@/hooks/useHandleData';
import { useUserStore } from '@/stores/modules/user';

defineOptions({
  name: 'datalistStatistics'
});

const proTableRef = ref<ProTableInstance>();
const fileRecordEditRef = ref<InstanceType<typeof FileRecordEdit>>();
const statisticsDialogRef = ref<InstanceType<typeof StatisticsDialog>>();
const userStore = useUserStore();

// 图片blob缓存
const imageBlobCache = new Map<string, string>();

// 使用axios获取带认证的图片并转换为blob URL
const getAuthenticatedImageUrl = async (url: string): Promise<string> => {
  if (!url || !userStore.token) return url;
  
  // 检查缓存
  if (imageBlobCache.has(url)) {
    return imageBlobCache.get(url)!;
  }
  
  try {
    console.log('Loading authenticated image:', url);
    
    // 使用axios获取图片，这样会自动添加认证头
    const response = await http.get(url, {}, { responseType: 'blob' });
    
    // 创建blob URL
    const blobUrl = URL.createObjectURL(response.data as Blob);
    
    // 缓存blob URL
    imageBlobCache.set(url, blobUrl);
    
    console.log('Image loaded successfully:', blobUrl);
    return blobUrl;
  } catch (error) {
    console.error('Failed to load authenticated image:', error);
    return url; // 返回原始URL作为fallback
  }
};

// 清理blob缓存的函数
const cleanupImageCache = () => {
  imageBlobCache.forEach(blobUrl => {
    URL.revokeObjectURL(blobUrl);
  });
  imageBlobCache.clear();
};

// 测试图片访问权限
const testImageAccess = async (originalUrl: string) => {
  try {
    console.log('Testing image access for:', originalUrl);
    
    // 方法1: 使用axios测试(带认证头)
    try {
      const response = await http.get(originalUrl, {}, { responseType: 'blob' });
      console.log('Axios with auth headers - Success:', response);
      ElMessage.success('图片可以通过认证头访问');
    } catch (axiosError) {
      console.error('Axios with auth headers failed:', axiosError);
    }
    
    // 方法2: 直接fetch测试(无认证头)
    try {
      const response = await fetch(originalUrl);
      console.log('Direct fetch response:', response.status, response.statusText);
      
      if (!response.ok) {
        const errorText = await response.text();
        console.log('Error response body:', errorText);
        ElMessage.warning(`直接访问失败: ${response.status} ${response.statusText}`);
      } else {
        ElMessage.success('图片可以直接访问(无需认证)');
      }
    } catch (fetchError) {
      console.error('Direct fetch failed:', fetchError);
      ElMessage.error('直接访问失败');
    }
    
  } catch (error) {
    console.error('Image access test failed:', error);
    ElMessage.error('测试访问失败');
  }
};

// 判断是否为图片文件
const isImageFile = (fileName: string, fileType?: string, fileUrl?: string) => {
  // 首先检查 fileType 是否包含具体的图片格式
  if (fileType) {
    const imageTypes = ['png', 'jpg', 'jpeg', 'gif', 'bmp', 'webp', 'svg'];
    const fileTypeLower = fileType.toLowerCase();
    if (imageTypes.some(type => fileTypeLower.includes(type))) {
      return true;
    }
  }
  
  // 检查 fileUrl 中是否包含图片路径或扩展名
  if (fileUrl) {
    const imageUrlPatterns = [
      '/images/', '/img/', '/picture/', '/pic/',
      '.jpg', '.jpeg', '.png', '.gif', '.bmp', '.webp', '.svg'
    ];
    const urlLower = fileUrl.toLowerCase();
    if (imageUrlPatterns.some(pattern => urlLower.includes(pattern))) {
      return true;
    }
  }
  
  // 最后检查文件名扩展名
  if (fileName) {
    const imageExtensions = ['.jpg', '.jpeg', '.png', '.gif', '.bmp', '.webp', '.svg'];
    return imageExtensions.some(ext => fileName.toLowerCase().endsWith(ext));
  }
  
  return false;
};

// 格式化文件大小
const formatFileSize = (size: number) => {
  if (size < 1024) return `${size} B`;
  if (size < 1024 * 1024) return `${(size / 1024).toFixed(2)} KB`;
  if (size < 1024 * 1024 * 1024) return `${(size / (1024 * 1024)).toFixed(2)} MB`;
  return `${(size / (1024 * 1024 * 1024)).toFixed(2)} GB`;
};

// 表格列配置
const columns: ColumnProps<MonitorFileRecordInfo>[] = [
  { type: 'selection', width: 80 },
  { type: 'index', label: '序号', width: 80 },
  { prop: 'newFilename', label: '新文件名', width: 200, showOverflowTooltip: true },
  { prop: 'originalFilename', label: '文件名', width: 200, showOverflowTooltip: true },
  { prop: 'fileTag', label: '设备编号', width: 200, showOverflowTooltip: true },
  { prop: 'carNumber', label: '车辆编号', showOverflowTooltip: true },
  { prop: 'carNumberRes', label: '图片文字', showOverflowTooltip: true },
  // { 
  //   prop: 'fileUrl', 
  //   label: '文件预览', 
  //   width: 120, 
  //   render: (scope) => {
  //     const { row } = scope;
  //     if (row.fileUrl && isImageFile(row.fileName, row.fileType, row.fileUrl)) {
  //       return h('div', {
  //         style: {
  //           width: '60px',
  //           height: '40px',
  //           display: 'flex',
  //           alignItems: 'center',
  //           justifyContent: 'center'
  //         }
  //       }, [
  //         h(AuthenticatedImage, {
  //           src: row.fileUrl,
  //           style: {
  //             width: '60px',
  //             height: '40px',
  //             borderRadius: '4px',
  //             cursor: 'pointer'
  //           }
  //         })
  //       ]);
  //     }
  //     return h('span', { style: { color: '#909399', fontSize: '12px' } }, '非图片文件');
  //   }
  // },
  // { prop: 'fileType', label: '文件类型', width: 120 },
  // { prop: 'fileSize', label: '文件大小', width: 120, render: (scope) => formatFileSize(scope.row.fileSize) },
  // { prop: 'uploadUser', label: '上传用户', width: 120 },
  // { prop: 'uploadTime', label: '上传时间', width: 180 },
  // { prop: 'status', label: '状态', width: 100, tag: true, render: (scope) => {
  //   const status = scope.row.status;
  //   const statusMap: { [key: string]: { text: string; type: string } } = {
  //     'PENDING': { text: '待处理', type: 'warning' },
  //     'PROCESSING': { text: '处理中', type: 'primary' },
  //     'SUCCESS': { text: '成功', type: 'success' },
  //     'FAILED': { text: '失败', type: 'danger' }
  //   };
  //   const statusInfo = statusMap[status] || { text: status, type: 'info' };
  //   return statusInfo.text;
  // }},
  // { prop: 'isProcessed', label: '是否处理', width: 100, render: (scope) => scope.row.isProcessed ? '是' : '否' },
  // { prop: 'processTime', label: '处理时间', width: 180, render: (scope) => scope.row.processTime || '未处理' },
  { prop: 'createTime', label: '创建时间', width: 180 },
  { prop: 'operation', label: '操作', width: 300, fixed: 'right' }
];

// 搜索条件项
const searchColumns: SearchProps[] = [
  // { prop: 'fileName', label: '文件名', el: 'input' },
  { prop: 'fileTag', label: '设备编号', el: 'input' },
  { prop: 'carNumber', label: '车辆编号', el: 'input' },
  {
    prop: 'carNumberEmpty',
    label: '是否有车辆编号',
    el: 'select',
    enum: [
      { label: '是', value: false },
      { label: '否', value: true }
    ],
    fieldNames: { label: 'label', value: 'value' }
  },
  // { prop: 'fileType', label: '文件类型', el: 'input' },
  // { prop: 'uploadUser', label: '上传用户', el: 'input' },
  // {
  //   prop: 'status',
  //   label: '状态',
  //   el: 'select',
  //   enum: [
  //     { label: '待处理', value: 'PENDING' },
  //     { label: '处理中', value: 'PROCESSING' },
  //     { label: '成功', value: 'SUCCESS' },
  //     { label: '失败', value: 'FAILED' }
  //   ],
  //   fieldNames: { label: 'label', value: 'value' }
  // },
  // {
  //   prop: 'isProcessed',
  //   label: '是否处理',
  //   el: 'select',
  //   enum: [
  //     { label: '是', value: true },
  //     { label: '否', value: false }
  //   ],
  //   fieldNames: { label: 'label', value: 'value' }
  // },
  // {
  //   prop: 'uploadTime',
  //   label: '上传时间',
  //   el: 'date-picker',
  //   span: 2,
  //   props: {
  //     type: 'datetimerange',
  //     valueFormat: 'YYYY-MM-DD HH:mm:ss',
  //     format: 'YYYY-MM-DD HH:mm:ss'
  //   }
  // }
];

// 获取table列表
const getTableList = (params: MonitorFileRecordQuery) => {
  const newParams = formatParams(params);
  return getMonitorFileRecordList(newParams);
};

// 格式化参数
const formatParams = (params: MonitorFileRecordQuery) => {
  const newParams = JSON.parse(JSON.stringify(params));
  
  // 处理上传时间范围
  if (newParams.uploadTime && Array.isArray(newParams.uploadTime)) {
    newParams.startDate = newParams.uploadTime[0];
    newParams.endDate = newParams.uploadTime[1];
    delete newParams.uploadTime;
  }
  
  // 处理是否有车辆编号的查询条件
  if (newParams.carNumberEmpty !== undefined && newParams.carNumberEmpty !== null) {
    newParams.carNumberEmpty = newParams.carNumberEmpty;
  }
  
  return newParams;
};

// 打开新增对话框
const openAdd = async () => {
  const params = {
    title: '新增文件记录',
    row: {},
    api: addMonitorFileRecord,
    getTableList: proTableRef.value?.getTableList
  };
  fileRecordEditRef.value?.acceptParams(params);
};

// 打开编辑对话框
const openEdit = async (row: MonitorFileRecordInfo) => {
  try {
    const params = {
      title: '编辑文件记录',
      row: { ...row },
      api: edit2MonitorFileRecord,
      getTableList: proTableRef.value?.getTableList
    };
    fileRecordEditRef.value?.acceptParams(params);
  } catch (error) {
    console.error('Open edit dialog error:', error);
    ElMessage.error('打开编辑对话框失败');
  }
};

// 查看文件记录详情
const viewFileRecord = (row: MonitorFileRecordInfo) => {
  // 如果是图片文件，显示图片预览对话框
  if (row.fileUrl && isImageFile(row.fileName, row.fileType, row.fileUrl)) {
    const authenticatedUrl = getAuthenticatedImageUrl(row.fileUrl);
    ElMessageBox({
      title: `文件详情 - ${row.fileName}`,
      message: h('div', { style: { textAlign: 'center' } }, [
        h('div', { 
          style: { 
            marginBottom: '20px',
            padding: '10px',
            backgroundColor: '#f5f7fa',
            borderRadius: '4px',
            fontSize: '14px',
            textAlign: 'left',
            whiteSpace: 'pre-line'
          }
        }, `文件名：${row.fileName}
文件类型：${row.fileType}
文件大小：${formatFileSize(row.fileSize)}
上传用户：${row.uploadUser}
上传时间：${row.uploadTime}
状态：${row.status}
是否处理：${row.isProcessed ? '是' : '否'}
处理时间：${row.processTime || '未处理'}
错误信息：${row.errorMessage || '无'}
备注：${row.remark || '无'}`),
        h('el-image', {
          src: authenticatedUrl,
          previewSrcList: [authenticatedUrl],
          fit: 'contain',
          style: {
            maxWidth: '100%',
            maxHeight: '400px',
            borderRadius: '8px',
            boxShadow: '0 2px 12px 0 rgba(0, 0, 0, 0.1)'
          },
          previewTeleported: true
        })
      ]),
      showCancelButton: false,
      confirmButtonText: '关闭',
      customStyle: {
        width: '600px'
      }
    });
  } else {
    // 非图片文件，显示文本信息
    ElMessageBox.alert(
      `
    文件名：${row.fileName}
    文件类型：${row.fileType}
    文件大小：${formatFileSize(row.fileSize)}
    上传用户：${row.uploadUser}
    上传时间：${row.uploadTime}
    状态：${row.status}
    是否处理：${row.isProcessed ? '是' : '否'}
    处理时间：${row.processTime || '未处理'}
    错误信息：${row.errorMessage || '无'}
    备注：${row.remark || '无'}
    创建时间：${row.createTime}
    更新时间：${row.updateTime}
    `,
      `文件记录详情 - ${row.fileName}`,
      {
        confirmButtonText: '关闭',
        customStyle: {
          'white-space': 'pre-line',
          'text-align': 'left'
        }
      }
    );
  }
};

// 下载文件
const downloadFileRecord = async (row: MonitorFileRecordInfo) => {
  try {
    if (!row.id) {
      ElMessage.warning('文件ID不存在');
      return;
    }
    
    ElMessage.info('开始下载文件...');
    const response = await downloadFile({ id: row.id });
    
    // 创建下载链接
    const responseData = response as any;
    const blob = new Blob([responseData.data || responseData]);
    const url = window.URL.createObjectURL(blob);
    const link = document.createElement('a');
    link.href = url;
    link.download = row.fileName;
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    window.URL.revokeObjectURL(url);
    
    ElMessage.success('文件下载成功');
  } catch (error) {
    console.error('Download file error:', error);
    ElMessage.error('文件下载失败');
  }
};

// 重新处理失败的文件
const reprocessFile = async (row: MonitorFileRecordInfo) => {
  try {
    if (!row.id) {
      ElMessage.warning('文件ID不存在');
      return;
    }
    
    await ElMessageBox.confirm(
      `确定要重新处理文件 "${row.fileName}" 吗？`,
      '重新处理',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    );
    
    await reprocessFailedFile({ id: row.id });
    ElMessage.success('重新处理成功');
    proTableRef.value?.getTableList();
  } catch (error) {
    if (error !== 'cancel') {
      console.error('Reprocess file error:', error);
      ElMessage.error('重新处理失败');
    }
  }
};

// 删除记录
const deleteRecord = async (row: MonitorFileRecordInfo) => {
  await useHandleData(deleteMonitorFileRecord, { ids: [row.id!] }, `删除文件记录 "${row.fileName}"`);
  proTableRef.value?.getTableList();
};

// 导出数据
const exportData = () => {
  ElMessage.info('导出功能待实现...');
};

// 获取统计信息
const getStatistics = async () => {
  try {
    statisticsDialogRef.value?.open();
  } catch (error) {
    console.error('Get statistics error:', error);
    ElMessage.error('获取统计信息失败');
  }
};

// 在组件卸载时清理图片缓存
onBeforeUnmount(() => {
  cleanupImageCache();
});
</script>